package com.woniu.map.remote;



import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.woniu.internalcommon.request.PointRequest;
import com.woniu.internalcommon.response.TraSearchResponse;
import com.woniu.internalcommon.response.TrackResponse;

import com.woniu.map.remote.url.YingYanUrl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

@Service
@Slf4j
public class TrackClient {
    @Value("${map.sxid}")
    private String amapSxid;

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private YingYanUrl yingYanURL;
    /**
     * 创建轨迹
     * @param tid 终端id
     *
     * @return 轨迹id
     */
    public TrackResponse addTrack(String tid,String trname){
        String url = yingYanURL.buildAddTrack(tid,amapSxid,trname);
        log.info("高德地图创建轨迹请求："+url);
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(url, null, String.class);
        String body = stringResponseEntity.getBody();
        log.info("高德地图创建轨迹响应："+body);
        return parseTrackResponse(body);
    }

    //处理请求体
   /**
        * 解析高德轨迹API响应
 * @param body API返回的JSON字符串
 * @return 轨迹响应数据
 * @throws IllegalArgumentException 当响应数据不合法时抛出
 */
    public TrackResponse parseTrackResponse(String body) {
        // 1. 参数校验
        if (StringUtils.isEmpty(body)) {
            throw new IllegalArgumentException("响应体不能为空");
        }
        // 2. 解析JSON
        JSONObject result = JSONObject.parseObject(body);
        if (result == null || !result.containsKey("data")) {
            throw new IllegalArgumentException("无效的API响应格式");
        }
        JSONObject data = result.getJSONObject("data");
        if (data == null) {
            throw new IllegalArgumentException("data返回值为空");
        }
        log.info("轨迹服务响应："+data);
        return new TrackResponse().setTrid(data.getString("trid")).
                setTrname(data.getOrDefault("trname", "").toString());
    }


    /**
     * 上传轨迹
     *
     */
    public String upload(PointRequest pointRequest){

        String url = yingYanURL.buildUploadTrack(pointRequest, amapSxid);
        log.info("高德地图上传轨迹请求："+url);
        log.info("高德地图上传地址："+pointRequest);
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(URI.create( url), null, String.class);
        String body = stringResponseEntity.getBody();
        log.info("高德地图上传轨迹响应字符串："+body);
        return  parseUpload(body);
    }
    /**
     * upload 转换JSON 映射实体类
     */
    public String parseUpload(String body){
        if (StringUtils.isEmpty( body)) {
            throw new IllegalArgumentException("upload响应体为空");
        }
        if (!body.contains("errcode")){
            throw new IllegalArgumentException("响应体格式错误");
        }
        JSONObject result = JSONObject.parseObject( body);
        if (result.getInteger("errcode") != 10000){
            throw new RuntimeException("上传轨迹失败 轨迹key不生效");
        }
        if (!result.containsKey("data")){
            throw new IllegalArgumentException("响应体格式错误");
        }
//        {"errcode":10000,"errmsg":"OK","data":{"errorpoints":[]}} errorpoints响应失败后部分成功信息
        log.info("上传轨迹服务响应："+result);
        return "ok";
    }

    /**
     * 查询某终端时间段的轨迹   用于计算驾驶时间
     * @param tid 终端tid
     * @param startTime 必填
     * @param endTime 必填
     * @return
     */
    public TraSearchResponse traSearch(String tid, Long startTime , Long endTime){
         log.info("轨迹查询参数：tid={},startTime={},endTime={}",tid,startTime,endTime);
//        TrsearchResponse

        String url = yingYanURL.buildTraSearch(tid, startTime,  endTime, amapSxid);

        log.info("高德地图查询轨迹结果请求："+url);
        ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
        log.info("高德地图查询轨迹结果响应："+forEntity);
        log.info("高德地图查询轨迹结果响应："+forEntity.getBody());
        return  parseTraSearch(forEntity.getBody());
    }

    /**
     * 解析轨迹查询结果
     * @param body
     * @return  driveMile 跑了多少米 ， driveTime 跑了多少分钟
     */
    private TraSearchResponse parseTraSearch(String body){
        log.info("轨迹查询服务响应body："+body);
        if (StringUtils.isEmpty(body)) {
            log.info("轨迹查询服务响应body："+body);
            throw new IllegalArgumentException("请求响应失败");
        }
        JSONObject result = JSONObject.parseObject(body);
        if (!result.get("errcode").equals(10000))
          throw  new IllegalArgumentException("参数错误 或认证失败");

        JSONObject data = result.getJSONObject("data");

        int counts = data.getIntValue("counts");
        log.info("轨迹查询服务响应2："+counts);
        if (counts == 0){
            return null;
        }
        log.info("轨迹查询服务响应："+data);
        JSONArray tracks = data.getJSONArray("tracks");
        AtomicLong driveMile = new AtomicLong(0L);
        AtomicLong driveTime = new AtomicLong(0L);
        /**
         * 要单独处理等时吗？
         */
        tracks.forEach(track -> {
            log.info("轨迹服务响应："+track);
             JSONObject jsonObject = (JSONObject) track;
              long distance = jsonObject.getLong("distance");
              long time = jsonObject.getLong("time");
            driveTime.set(driveTime.get() + time/ (1000 * 60));
            driveMile.set(driveMile.get() + distance);
        });

   return  new TraSearchResponse().setDriveMile(driveMile.get()).setDriveTime(driveTime.get());
    }





//    {
//        "errcode": 10000,
//            "errmsg": "OK",
//            "data": {
//        "tracks": [
//        {
//            "startPoint": {
//            "location": "116.618003,39.927718",
//                    "locatetime": 1752205815478
//        },
//            "endPoint": {
//            "location": "116.615574,39.924477",
//                    "locatetime": 1752207447109
//        },
//            "trid": 219,
//                "distance": 416,
//                "time": 1631631,
//                "counts": 2,
//                "points": [
//            {
//                "location": "116.618003,39.927718",
//                    "locatetime": 1752205815478,
//                    "speed": 255,
//                    "direction": 511,
//                    "accuracy": 550
//            },
//            {
//                "location": "116.615574,39.924477",
//                    "locatetime": 1752207447109,
//                    "speed": 255,
//                    "direction": 511,
//                    "accuracy": 550
//            }
//				]
//        },
//        {
//            "trid": 120,
//                "distance": 0,
//                "time": 1631631,
//                "counts": 0,
//                "points": []
//        }
//		],
//        "counts": 2
//    }
//    }



}

